from django.http import HttpResponse

import urllib2
import os
import csv

from stock.models import StockPrice
from datetime import datetime,timedelta

def bualuang2DB(inputDate):
  url = "http://realtime.bualuang.co.th/myeasy/realtime/quotation/txt/"+inputDate+".txt"
  # bualuang format
  # e.g. http://realtime.bualuang.co.th/myeasy/realtime/quotation/txt/09122011.txt
  result = None
  try: 
    result = urllib2.urlopen(url)
  except urllib2.HTTPError, e:
    error =  'Error code: ' + str(e.code)
  except urllib2.URLError, e:
    error = 'Reason: ' + e.reason    
  else :
    if result.code == 200:
      error = loadData2DB(result,inputDate) 
  return inputDate + " - " + error
    
def loadWeb2DBnow(request):
  latestData = StockPrice.objects.only('Date').latest('Date').Date
  now = datetime.now()
  oneday = timedelta(days=1)
  latestData = latestData + oneday
  
  response = HttpResponse()
  response.write("From : " + str(latestData.strftime('%d%m%Y')) + "<br />")
  response.write("To : " + str(now) + "<br />")
  while((abs(now - latestData)).days > 0):
    inputDate = str(latestData.strftime('%d%m%Y'))
    error = bualuang2DB(inputDate)
    response.write(error + "<br />")
    latestData = latestData + oneday
    print error
  return response
  
def loadWeb2DB(request,inputDate):
  error = bualuang2DB(inputDate)  
  return HttpResponse(error + inputDate)

def loadFile2DB(request):  
  current_folder = "./Price"
  list_file = [f for f in os.listdir(current_folder) if os.path.isfile(os.path.join(current_folder, f))]
  print "Process : ", current_folder+"/", list_file[0]
  for pfile in list_file :
    f = open(os.path.join(current_folder, pfile), 'r')
    d = pfile.split('.')[0]
    error = loadData2DB(f,d)
    f.close()
    print error,pfile
  return HttpResponse('Done')
  
def loadFile2DBMetaStockFormat(request):
  ### if use sqlite, uncomment 4 line below to speed up initial database
  #from django.db import connection
  #cursor = connection.cursor()
  #cursor.execute('PRAGMA temp_store = MEMORY;')
  #cursor.execute('PRAGMA synchronous=OFF')
  
  current_folder = os.path.realpath(os.path.dirname(__file__)) + "/../Price/MetaStock"
  list_file = [f for f in os.listdir(current_folder) if os.path.isfile(os.path.join(current_folder, f))]
  print "Process : ", current_folder+"/", list_file[0]
  count = 0
  for pfile in list_file :
    count = count + 1
    print count,pfile,
    f = open(os.path.join(current_folder, pfile), 'r')
    fdr = csv.DictReader(f, delimiter=',')
    for stock in fdr:
      stockDate = datetime.date(datetime.strptime(stock['<DTYYYYMMDD>'],'%Y%m%d'))
      s = StockPrice(Name=stock['<TICKER>'],
        Date=stockDate,
        Open=float(stock['<OPEN>']),
        High=float(stock['<HIGH>']),
        Low=float(stock['<LOW>']),
        Close=float(stock['<CLOSE>']),
        Change=0,
        PChange=0,
        Vol=int(stock['<VOL>']),
        Val=int(stock['<VOL>'])*float(stock['<CLOSE>']))
      s.save()    
    f.close()
    print 'Complete'
  return HttpResponse('Done')
      
def loadData2DB(datainput,inputDate):
  data = datainput.readline()
  #print len(data)
  while data :
    count = 0
    if len(data) != 84 :
      data = datainput.readline()
      continue

    stockName = data[count:count+8].strip()
    stockDate = datetime.date(datetime.strptime(data[count+9:count+15],'%y%m%d'))
    currentDate = datetime.date(datetime.strptime(inputDate,'%d%m%Y'))
    #print stockName  
    
    if currentDate != stockDate :
      data = datainput.readline()
      continue
    
    try :
      checkData = StockPrice.objects.all().filter(Name=stockName).filter(Date=stockDate).get()
    except StockPrice.DoesNotExist :
      s = StockPrice(Name=stockName,
        Date=stockDate,
        Open=float(data[count+16:count+24]),
        High=float(data[count+25:count+33]),
        Low=float(data[count+34:count+42]),
        Close=float(data[count+43:count+51]),
        Change=0,
        PChange=0,
        Vol=int(data[count+52:count+67]),
        Val=int(data[count+68:count+83]))
      s.save()
    data = datainput.readline()
  error = 'Done ' 
  return error
  